/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2024-11-08
 * Time: 19:41
 */
public class SymmetricMatrix {
    private int size;
    private int[] elements;
    private int[] indices;
    private int nonZeroCount;

    public SymmetricMatrix(int size) {
        this.size = size;
        this.elements = new int[size * (size + 1) / 2];
        this.indices = new int[size * (size + 1) / 2];
        this.nonZeroCount = 0;
    }

    public void set(int i, int j, int value) {
        if (i > j) {
            int temp = i;
            i = j;
            j = temp;
        }
        int index = (i * (i - 1) / 2) + j;
        this.indices[index] = j;
        if (value != 0) {
            this.elements[index] = value;
            nonZeroCount++;
        } else if (this.elements[index] != 0) {
            this.elements[index] = 0;
            nonZeroCount--;
        }
    }

    public int get(int i, int j) {
        if (i > j) {
            int temp = i;
            i = j;
            j = temp;
        }
        int index = (i * (i - 1) / 2) + j;
        return this.elements[index];
    }

    public void addMatrix(SymmetricMatrix B) {
        for (int i = 0; i < B.size; i++) {
            for (int j = i; j < B.size; j++) {
                int indexA = (i * (i - 1) / 2) + j;
                int indexB = (i * (i - 1) / 2) + j;
                int valueA = this.elements[indexA];
                int valueB = B.elements[indexB];
                int sum = valueA + valueB;
                this.elements[indexA] = sum;
                if (sum != 0) {
                    this.indices[indexA] = j;
                    this.nonZeroCount++;
                } else if (valueA == 0 && valueB != 0) {
                    this.nonZeroCount--;
                }
            }
        }
    }

    public void printMatrix() {
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                if (i > j) {
                    System.out.print(this.get(j, i) + " ");
                } else {
                    System.out.print(this.get(i, j) + " ");
                }
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        SymmetricMatrix A = new SymmetricMatrix(3);
        SymmetricMatrix B = new SymmetricMatrix(3);

        A.set(0, 0, 1);
        A.set(1, 1, 2);
        A.set(2, 2, 3);
        A.set(0, 1, 4);
        A.set(0, 2, 5);
        A.set(1, 2, 6);

        B.set(0, 0, 7);
        B.set(1, 1, 8);
        B.set(2, 2, 9);
        B.set(0, 1, 10);
        B.set(0, 2, 11);
        B.set(1, 2, 12);

        System.out.println("Matrix A:");
        A.printMatrix();
        System.out.println("\nMatrix B:");
        B.printMatrix();

        A.addMatrix(B);

        System.out.println("\nMatrix A after A = A + B:");
        A.printMatrix();
    }
}